#include "StdAfx.h"
#include "RandomImage.h"

CRandomImage* CRandomImage::m_pInstance = NULL;

CRandomImage::CRandomImage(void)
{
}

CRandomImage::~CRandomImage(void)
{
}

void CRandomImage::init(LPTSTR path)
{
	m_lptPath = path;

	search(m_lptPath);
}

void CRandomImage::search(LPTSTR path)
{
	HANDLE hFind;  
	WIN32_FIND_DATA wfd;  
	TCHAR tempPath[MAX_PATH];  

	ZeroMemory(&wfd, sizeof(WIN32_FIND_DATA));  
	
	memset(tempPath, 0, sizeof(tempPath));  
	sprintf(tempPath, "%s\\*.*", path);  

	hFind = FindFirstFile(tempPath, &wfd);  
	if(INVALID_HANDLE_VALUE == hFind)  
	{  
		return;  
	}  
	do  
	{  
		if('.' == wfd.cFileName[0])  
		{  
			continue;  
		}  

		if(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)  
		{  
			sprintf(tempPath, "%s\\%s", path, wfd.cFileName);  

			search(tempPath);  
		}  
		else  
		{  
			sprintf(tempPath, "%s\\%s", path, wfd.cFileName);  
			m_strPathArray.Add(tempPath);
		}  
	}while(FindNextFile(hFind, &wfd));  
	
	FindClose(hFind);  
}

const CString CRandomImage::getRandomImage()
{
	INT32 length = m_strPathArray.GetCount();
	if (length == 0) {
		return _T("");
	}

	{
		srand((unsigned)time(NULL));
		m_iRandomIndex = rand() % length;
	}while(m_iRandomIndex == length);
	

	return m_strPathArray.GetAt(m_iRandomIndex);
}
